package com.coordinate.servlets;

import com.coordinate.services.*;
import com.coordinate.servlets.VoiceMessage;

import com.twilio.sdk.*;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.google.appengine.api.datastore.Blob;

import com.coordinate.db.*;

import javax.servlet.http.*;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;


import org.apache.commons.io.IOUtils;

@SuppressWarnings("serial")
public class Text2SpeechVoiceCallsWorker extends HttpServlet 
{
	
	public static final String APIVERSION = "2008-08-01";
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException 
	{
		   TwilioRestClient lClient = new TwilioRestClient("AC77943b640133a1753309c10b540ab3fe","162fb8a1140d3085fed1584d5250ee18",null);
		   
		   System.out.println("Placing outgoing call to "+ req.getParameter("mobile_number") +" with vm_key"+ req.getParameter("vm_key"));
		   makeCallExample(lClient,"8669296421",req.getParameter("mobile_number"),"http://egov-innovations.appspot.com/TwilXml?vm_key="+req.getParameter("vm_key"));
	       resp.getOutputStream().close();
	             
	 }
	
	private void makeCallExample(TwilioRestClient client, String caller, String called, String url ){

        //build map of post parameters 
        Map<String,String> params = new HashMap<String,String>();
        params.put("Caller", caller);
        params.put("Called", called);
        params.put("Url", url);
        TwilioRestResponse response;
        
        try {
            response = client.request("/"+APIVERSION+"/Accounts/"+client.getAccountSid()+"/Calls", "POST", params);
        
            if(response.isError())
                System.out.println("Error making outgoing call: "+response.getHttpStatus()+"\n"+response.getResponseText());
            else {
                System.out.println(response.getResponseText());

            }
        } catch (TwilioRestException e) {
            e.printStackTrace();
        }
    }
	
}
